<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

use View;
use DB;
use Session;
use Redirect;
use App\Model\Menu;
use App\Model\User;

class IndexController extends Controller
{
	 
	/**
	 * 后台控制主架构
	 */
	public function index()
	{
		$menu_list = Menu::where(['menu_parent_id' => 0, 'menu_status' => 1])->orderBy('menu_sort','asc')->get()->toArray();
		if ($menu_list) {
			foreach ($menu_list as $key => $value) {
				$menu_list[$key]['soninfo'] = Menu::where(['menu_parent_id' => $value['menu_id'], 'menu_status' => 1])->orderBy('menu_sort','asc')->get()->toArray();
			}
		}
		$admin_user = Session::get('adminuser')->toArray();
		return View::make('admin.index.index', ['menulist' => $menu_list, 'adminuser' => $admin_user]);
	}

	/**
	 * 后台控制主页面
	 */
	public function welcome()
	{
		$siteInfo = DB::table('systemset_website')->first();
		return View::make('admin.index.welcome', ['siteinfo' => $siteInfo]);
	}

	/**
	 * 后台登陆页面
	 */
	public function login()
	{
		return View::make('admin.index.login');
	}

	/**
	 * 后台登陆方法
	 */
	public function toLogin(Requests\UserLoginRequest $request)
	{
		$data = $request->all();
		$userInfo = User::where('user_name', $data['user_name'])->first();
		if (count($userInfo) == 0) {
            $jsonData = $this->getJsonData(0,'用户名不存在');
        } else {
        	$check_pwd = Hash::check($data['user_password'] , $userInfo->user_password);
        	if (!$check_pwd) {
                $jsonData = $this->getJsonData(0,'密码错误');
        	}
        	if (!$userInfo->user_status) {
                $jsonData = $this->getJsonData(0,'账号已被禁用，请联系总管理员');
        	}
        }
        if(!isset($jsonData)) {
        	$update_data = [
        		'user_last_login_time' => time(),
        		'user_last_login_ip'   => $request->getClientIp(),
        	];
        	User::where('user_id',$userInfo->user_id)->update($update_data);
        	session(['adminuser' => $userInfo]);
            $jsonData = $this->getJsonData(1,'登陆成功','/admin');
        }
        return response()->json($jsonData);
	}
	
	/**
     *  后台退出操作
     */
    public function logout()
    {
        Session::forget('adminuser');
        return Redirect::to('/admin/login');
    }
}